if (typeof  treeJs == 'undefined') {
    var treeJs = {};
    treeJs.form = $("#validation-form");
    /**移动按钮*/
    treeJs.move = function (treeNode1, treeNode2) {
        $.getJSON(ctx + "/organization/sort", {id1: treeNode1.id, id2: treeNode2.id}, function (data) {
            if (data && data.status == "SUCCESS") {
                treeJs.treeObj.moveNode(treeNode1, treeNode2, "prev");
            } else {
                $.messager.alert(data ? data.body : "系统错误,请稍后再试");
            }
        });
    }
    /**保存*/
    treeJs.save = function (treeNode, type) {
        if (!treeJs.checkForm().form()) {
            return false;
        }
        if (type == "edit") {
            $.getJSON(ctx + "/organization/update", treeJs.form.serialize(), function (data) {
                $.messager.alert(data.body);
                if (data && data.status == "SUCCESS") {
                    treeNode.name = $("[name='name']").val();
                    treeNode.description = $("[name='description']").val();
                    treeNode.isEnabled = $("[name='isEnabled']:checked").val();
                    treeJs.treeObj.updateNode(treeNode);
                }
            });
        }
        else {
            $.getJSON(ctx + "/organization/insert", treeJs.form.serialize(), function (data) {
                $.messager.alert(data.body);
                if (data && data.status == "SUCCESS") {
                    $("[name='id']").val(data.data);//保存后返回ID
                    var newNode = {
                        id: data.data,
                        name: $("[name='name']").val(),
                        description:$("[name='description']").val(),
                        isEnabled: $("[name='isEnabled']:checked").val()
                    };
                    newNode = treeJs.treeObj.addNodes(treeNode, newNode);
                    treeJs.treeObj.selectNode(newNode);
                    treeJs.form.hide();
                }
            });
        }
    }
    /**添加按钮*/
    treeJs.add = function (treeNode) {
        treeJs.form.get(0).reset();//清空表单
        var parentName = treeNode.name;//这里是被点击的节点的名称
        var parentId = treeNode.id;//这里是被点击的节点的ID
        $("[name='parentName']").val(parentName);
        $("[name='parentId']").val(parentId);
        $("[name='id']").val("");
        $(":radio").prop("checked", false);
        treeJs.form.show();
        $("#saveBtn").unbind().bind("click", function () {
            treeJs.save(treeNode, "new");
        });
    }
    /**删除按钮*/
    treeJs.delete = function (treeNode) {
        var len = treeNode.children ? treeNode.children.length : 0;
        //ajax查询下级count
        if (len == 0) {

        }
        if (len > 0) {
            $.messager.alert("请先删除子节点");
            return;
        } else {
            $.messager.confirm("确认要删除" + treeNode.name + "吗?", function (ck) {
                if (ck) {
                    //隐藏右侧表单
                    if ($("[name='id']").val() == treeNode.id) {
                        treeJs.form.hide();
                    }
                    $.getJSON(ctx + "/organization/delete", {id: treeNode.id}, function (data) {
                        if (data && data.status == "SUCCESS") {
                            var pNode = treeNode.getParentNode();
                            treeJs.treeObj.removeNode(treeNode);
                            var childLength = pNode.children.length;
                            if (childLength == 0) {
                                pNode.isParent = false;
                                treeJs.treeObj.updateNode(pNode);
                            }
                            $.messager.alert("删除成功");
                        }
                    });
                }
            });
        }
    }
    /**表单验证*/
    treeJs.checkForm = function () {
        return $('#validation-form').validate({
            rules: {
                name: {
                    required: true
                }
            }
        });
    }
    /**节点单击*/
    treeJs.nodeClick = function (event, treeId, treeNode) {
        treeJs.form.get(0).reset();
        treeJs.form.hide();
        if (treeNode.level == 0) {
            return;
        }
        var parentName = treeNode.getParentNode().name;
        var parentId = treeNode.getParentNode().id;
        $("[name='parentId']").val(parentId);
        $("[name='parentName']").val(parentName);
        $("[name='id']").val(treeNode.id);
        $("[name='name']").val(treeNode.name);
        $("[name='isEnabled'][value='" + treeNode.isEnabled + "']").prop("checked", true);
        $("[name='description']").val(treeNode.description);
        treeJs.form.show();
        $("#saveBtn").unbind().bind("click", function () {
            treeJs.save(treeNode, "edit");
        });
        event.stopPropagation();
    }


    treeJs.setting = {
        view: {
            addHoverDom: function (treeId, treeNode) {
                var aObj = $("#" + treeNode.tId + "_a");
                if ($("#btnSpan_" + treeNode.id).size() != 0) {
                    return;
                }
                var btns = (treeNode.level == 0 ) ? [] : [
                    "<a type='button' id='diyBtn1_" + treeNode.id + "' title='向上移动' onfocus='this.blur();'><i class='glyphicon glyphicon-circle-arrow-up'></i></a>",
                    "<a type='button' id='diyBtn2_" + treeNode.id + "' title='向下移动' onfocus='this.blur();'><i class='glyphicon glyphicon-circle-arrow-down'></i></a>",
                    "<a type='button' id='diyBtn3_" + treeNode.id + "' title='添加'     onfocus='this.blur();'><i class='glyphicon glyphicon-plus-sign'></i></a>",
                    "<a type='button' id='diyBtn4_" + treeNode.id + "' title='删除'     onfocus='this.blur();'><i class='glyphicon glyphicon-remove'></i></a>"
                ];
                aObj.append("<span id='btnSpan_" + treeNode.id + "' >" + btns.join("") + "</span>");
                var upBtn = $("#diyBtn1_" + treeNode.id);
                if (upBtn) {
                    upBtn.bind("click", function () {
                        var brother = treeNode.getPreNode();
                        if (brother == null) {
                            $.messager.alert("已经是第一个节点，不能向上移动");
                            return;
                        }
                        treeJs.move(treeNode.getPreNode(), treeNode);
                    });
                }
                var downBtn = $("#diyBtn2_" + treeNode.id);
                if (downBtn) {
                    downBtn.bind("click", function () {
                        var brother = treeNode.getNextNode();
                        if (brother == null) {
                            $.messager.alert("已经是最后一个节点，不能向下移动");
                            return;
                        }
                        treeJs.move(treeNode, treeNode.getNextNode());
                    });
                }

                //添加
                var addBtn = $("#diyBtn3_" + treeNode.id);
                if (addBtn) {
                    addBtn.bind("click", function (e) {//“添加”按钮点击事件
                        treeJs.add(treeNode);
                        e.stopPropagation();
                    });
                }

                var deleteBtn = $("#diyBtn4_" + treeNode.id);
                if (deleteBtn) {
                    deleteBtn.bind("click", function (e) {
                        treeJs.delete(treeNode);
                        e.stopPropagation();
                    });
                }
            },
            removeHoverDom: function (treeId, treeNode) {
                $("#btnSpan_" + treeNode.id + " a").unbind().remove();
                $("#btnSpan_" + treeNode.id).unbind().remove();
            }
        },
        async: {
            enable: true,
            url: ctx + "/organization/list",
            autoParam: ["id"],
            dataFilter: function (treeId, parentNode, childNodes) {
                if (!childNodes) return null;
                for (var i = 0, l = childNodes.length; i < l; i++) {
                    childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
                }
                return childNodes;
            }
        },
        edit: {
            showRemoveBtn: false,
            enable: true,
            showRenameBtn: false
        },
        callback: {
            onClick: treeJs.nodeClick
        }
    }
}

$(function () {
    $.fn.zTree.init($("#treeView"), treeJs.setting);
    treeJs.treeObj = $.fn.zTree.getZTreeObj("treeView");
    $("#resetBtn").bind("click",function (){
        treeJs.form.get(0).reset();
    });
});





